package fiscal.gui.classificacao;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


import exceptions.PersistenceExceptionMessage;
import fiscal.action.ClassificacaoActionsManager;
import fiscal.entities.tables.Classificacao;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Color;
import javax.swing.ListSelectionModel;

@SuppressWarnings("serial")
public class ClassificacaoPesquisa extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JTextField textField;
	private JLabel lblDescrico;
	private JButton btnPesquisar;
	private JButton btnSelecionar;
	private JButton btnSair;
	private JPanel panel;
	private JScrollPane scrollPane;
	private JTable table;
	
	private ClassificacaoActionsManager action;
	private Classificacao classificacao;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		
		try {
			new ClassificacaoPesquisa().setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */
	public ClassificacaoPesquisa() {
		try {
			setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			setBounds(100, 100, 567, 359);
			setResizable(false);
			setLocationRelativeTo(null);
			setModal(true);
			getContentPane().setLayout(null);
			contentPanel.setBounds(0, 0, 561, 327);
			contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
			getContentPane().add(contentPanel);
			contentPanel.setLayout(null);
			contentPanel.add(getTextField());
			contentPanel.add(getBtnPesquisar());
			contentPanel.add(getLblDescrico());
			contentPanel.add(getPanel());
			contentPanel.add(getBtnSelecionar());
			contentPanel.add(getBtnSair());

			setTableBackground(new Color(255, 255, 252));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private JTextField getTextField() {
		if (textField == null) {
			textField = new JTextField("");
			textField.setBounds(22, 25, 429, 23);
			textField.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					if (arg0.getKeyChar() == KeyEvent.VK_ENTER || arg0.getKeyCode() == 40)
						getBtnPesquisar().requestFocus();
				}
			});
			textField.setColumns(10);
		}
		return textField;
	}
	private JLabel getLblDescrico() {
		if (lblDescrico == null) {
			lblDescrico = new JLabel("Descri\u00E7\u00E3o");
			lblDescrico.setBounds(22, 11, 106, 14);
		}
		return lblDescrico;
	}
	
	private JButton getBtnPesquisar() {
		if (btnPesquisar == null) {
			btnPesquisar = new JButton("Pesquisar");
			btnPesquisar.setBounds(455, 25, 81, 23);
			btnPesquisar.setToolTipText("Realizar busca");
			btnPesquisar.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					if (arg0.getKeyCode() == 38)
						getTextField().requestFocus();
					if (arg0.getKeyCode() == 40)
						getTable().requestFocus();
				}
			});
			btnPesquisar.setMnemonic('p');
			btnPesquisar.addActionListener(new ActionListener() {
				
				public void actionPerformed(ActionEvent arg0) {
					int cont = getTable().getRowCount() - 1;
					while(cont >= 0) {
						((DefaultTableModel) getTable().getModel()).removeRow(cont);
						cont--;
					}
					
					ArrayList<Classificacao> classificacaos = new ArrayList<Classificacao>();
					try {
						if (getAction().eNumero(getTextField().getText().trim()) || getAction().eNumero(getAction().tiraMask(getTextField().getText().trim()))) 								
							classificacaos = getAction().findByIdLike(getAction().tiraMask(getTextField().getText().trim()));
						else 
							classificacaos = getAction().findByDescricaoLike(getTextField().getText().trim());
						for (final Classificacao classificacao : classificacaos) {
							Object classifs[] = {classificacao, classificacao.getDescricao()};
							((DefaultTableModel) getTable().getModel()).addRow(classifs);
						}
					} catch (PersistenceExceptionMessage e) {
						// TODO Auto-generated catch block
						//e.printStackTrace();
					}
				}
			});
		}
		return btnPesquisar;
	}
	private JButton getBtnSelecionar() {
		if (btnSelecionar == null) {
			btnSelecionar = new JButton("Selecionar");
			btnSelecionar.setBounds(191, 280, 81, 23);
			btnSelecionar.setToolTipText("Selecionar item");
			btnSelecionar.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					setObjetoSelecionado();
					if (getClassificacao() != null)
						dispose();
				}
			});
			btnSelecionar.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					if (e.getKeyCode() == 38)
						getTable().requestFocus();
					if (e.getKeyCode() == 40)
						getBtnSair().requestFocus();
				}
			});
			btnSelecionar.setMnemonic('s');
		}
		return btnSelecionar;
	}
	private JButton getBtnSair() {
		if (btnSair == null) {
			btnSair = new JButton("Sair");
			btnSair.setBounds(278, 280, 81, 23);
			btnSair.setToolTipText("Sair da busca");
			btnSair.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					if (e.getKeyCode() == 38)
						getBtnSelecionar().requestFocus();
					if (e.getKeyCode() == 40)
						getTextField().requestFocus();
				}
			});
			btnSair.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					dispose();
				}
			});
			btnSair.setMnemonic('r');
		}
		return btnSair;
	}
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setBounds(22, 59, 512, 204);
			panel.setBorder(new TitledBorder(null, "Resultado da Pesquisa", TitledBorder.LEADING, TitledBorder.TOP, null, null));
			GroupLayout gl_panel = new GroupLayout(panel);
			gl_panel.setHorizontalGroup(
				gl_panel.createParallelGroup(Alignment.LEADING)
					.addComponent(getScrollPane(), GroupLayout.DEFAULT_SIZE, 523, Short.MAX_VALUE)
			);
			gl_panel.setVerticalGroup(
				gl_panel.createParallelGroup(Alignment.LEADING)
					.addGroup(gl_panel.createSequentialGroup()
						.addComponent(getScrollPane(), GroupLayout.PREFERRED_SIZE, 181, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
			);
			panel.setLayout(gl_panel);
		}
		return panel;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}
	public void setObjetoSelecionado() {
		int linha = getTable().getSelectedRow();
		if (linha > -1)
			setClassificacao((Classificacao) getTable().getModel().getValueAt(linha, 0));
	}
	private JTable getTable() {
		if (table == null) {
			table = new JTable();
			table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			table.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					if (arg0.getClickCount() == 2) {
						setObjetoSelecionado();
						if (getClassificacao() != null)
							dispose();
					}
				}
			});
			table.setToolTipText("Duplo click ou enter para selecionar.");
			table.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					if (e.getKeyChar() == KeyEvent.VK_ENTER || e.getKeyCode() == 39){
						getBtnSelecionar().requestFocus();
					}
					if (e.getKeyCode() == 37)
						getBtnPesquisar().requestFocus();
				}
			});
			table.setModel(new DefaultTableModel(
				new Object[][] {
				},
				new String[] {
					"Classifica\u00E7\u00E3o", "Descri\u00E7\u00E3o"
				}
			) {
				boolean[] columnEditables = new boolean[] {
					false, false
				};
				public boolean isCellEditable(int row, int column) {
					return columnEditables[column];
				}
			});
			table.getColumnModel().getColumn(0).setResizable(false);
			table.getColumnModel().getColumn(0).setPreferredWidth(90);
			table.getColumnModel().getColumn(1).setResizable(false);
			table.getColumnModel().getColumn(1).setPreferredWidth(402);
			table.getColumnModel().getColumn(1).setMinWidth(250);
			table.getColumnModel().getColumn(1).setMaxWidth(402);
		}
		return table;
	}

	public ClassificacaoActionsManager getAction() {
		if (action == null) {
			action = new ClassificacaoActionsManager();
		}
		return action;
	}

	public void setAction(ClassificacaoActionsManager action) {
		this.action = action;
	}

	public Classificacao getClassificacao() {
		return classificacao;
	}

	public void setClassificacao(Classificacao classificacao) {
		this.classificacao = classificacao;
	}
	public Color getTableBackground() {
		return getTable().getBackground();
	}
	public void setTableBackground(Color background) {
		getTable().setBackground(background);
		getTable().getParent().setBackground(background);
	}
}
